package com.example.lettcode.cron;

import org.quartz.CronTrigger;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.TriggerUtils;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

public class PreviousExecutionTime {

    public static Date getPreviousExecutionTime(String cronExpression, Date startDate, Date endDate) throws ParseException {
        CronTriggerImpl cronTrigger = new CronTriggerImpl();
        cronTrigger.setCronExpression(cronExpression);

        // 计算指定时间范围内的所有执行时间
        List<Date> fireTimes = TriggerUtils.computeFireTimesBetween(cronTrigger, null, startDate, endDate);

        if (fireTimes != null && !fireTimes.isEmpty()) {
            // 找到最接近结束时间的上一个执行时间
            fireTimes.sort(null); // 确保列表是按时间排序的
            return fireTimes.get(fireTimes.size() - 1);
        }

        return null; // 如果没有找到，返回null
    }

    public static void main(String[] args) {
        try {
            String cronExpression = "0 0 2 9,15,20 * ?"; // 每天的9点、15点和20点的2点执行
            Date startDate = new Date(System.currentTimeMillis() - 3600 * 24 * 1000); // 自定义开始时间，例如一天前
            Date endDate = new Date(); // 结束时间为当前时间

            Date previousExecutionTime = getPreviousExecutionTime(cronExpression, startDate, endDate);
            if (previousExecutionTime != null) {
                System.out.println("The previous execution time is: " + previousExecutionTime);
            } else {
                System.out.println("No previous execution time found within the specified range.");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}